﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class XunJianShuJuController : BaseController
    {
        private readonly ILogger<XunJianShuJuController> _logger;
        public XunJianShuJuController(ILogger<XunJianShuJuController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] string duty, [FromForm] string inspector, [FromForm] string status, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            ISelect<XunJianShuJu> iselect = _fsql.Select<XunJianShuJu>().OrderBy("id desc").WhereIf(begintime != DateTime.MinValue, xjsj => xjsj.Xjsj >= begintime).WhereIf(endtime != DateTime.MinValue, xjsj => xjsj.Xjsj <= endtime).WhereIf(!string.IsNullOrEmpty(duty), xjsj => xjsj.Duty == duty).WhereIf(!string.IsNullOrEmpty(inspector), xjsj => xjsj.Inspector == inspector).WhereIf(!string.IsNullOrEmpty(status), xjsj => xjsj.Status == status);
            List<XunJianShuJu> users;
            long total = -1;
            if (doPage == 0)
            {
                users = await iselect.ToListAsync();
            }
            else
            {
                users = await iselect.Count(out total).Page(pageNumber, pageSize).ToListAsync();
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("data", users == null ? null : JArray.FromObject(users));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] string data, [FromForm] string daan)
        {
            List<XunJianShuJu> xunjianshujus = JsonConvert.DeserializeObject<List<XunJianShuJu>>(data);

            int affrows = 0;
            XunJianShuJu xunjianshuju = await _fsql.Select<XunJianShuJu>().Where(xjsj => xjsj.Rwid == xunjianshujus[0].Rwid).ToOneAsync();
            if (xunjianshuju != null) {
                return RenderJson(status: "failed", message: "该任务已关闭", code: 3005, data: null);
            }
            _fsql.Transaction(() => {
                // 添加List巡检数据
                affrows = _fsql.Insert(xunjianshujus).ExecuteAffrows();
                // 关闭任务
                _fsql.Update<RenWu>(xunjianshujus[0]?.Rwid).Set(rw => rw.Daan, daan).Set(rw => rw.Status, "已关闭").ExecuteAffrows();
            });
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] XunJianShuJu xunjianshuju) {
            int affrows = await _fsql.Update<XunJianShuJu>().SetSource(xunjianshuju).ExecuteAffrowsAsync();

            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            XunJianShuJu xunjianshuju = await _fsql.Select<XunJianShuJu>().Where(xjsj => xjsj.Id == id).ToOneAsync();

            return RenderJson(data: xunjianshuju);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Echarts([FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] string duty, [FromForm] string inspector)
        {
            Dictionary<string, long> tb1 = new();
            Dictionary<string, long> tb2 = new();
            List<LuXian> luxians = await _fsql.Select<LuXian>().ToListAsync();
            foreach (var lx in luxians)
            {
                string tb1_sbmc = lx.Xjx + "(" + lx.Lxmc + ")";
                long tb1_count = _fsql.Select<XunJianShuJu>()
                    .WhereIf(begintime != DateTime.MinValue, xjsj => xjsj.Xjsj >= begintime).WhereIf(endtime != DateTime.MinValue, xjsj => xjsj.Xjsj <= endtime).WhereIf(!string.IsNullOrEmpty(duty), xjsj => xjsj.Duty == duty).WhereIf(!string.IsNullOrEmpty(inspector), xjsj => xjsj.Inspector == inspector)
                    .Where(xjsj => xjsj.Sbid == lx.Id && xjsj.Status == "异常").Count();

                string tb2_sbmc = tb1_sbmc;
                long tb2_count = _fsql.Select<XunJianShuJu>()
                    .WhereIf(begintime != DateTime.MinValue, xjsj => xjsj.Xjsj >= begintime).WhereIf(endtime != DateTime.MinValue, xjsj => xjsj.Xjsj <= endtime).WhereIf(!string.IsNullOrEmpty(duty), xjsj => xjsj.Duty == duty).WhereIf(!string.IsNullOrEmpty(inspector), xjsj => xjsj.Inspector == inspector)
                    .Where(xjsj => xjsj.Sbid == lx.Id && xjsj.Status != "未检").Count();

                tb1.Add(tb1_sbmc, tb1_count);
                tb2.Add(tb2_sbmc, tb2_count);
            }
            tb1 = (from tb1dic in tb1 orderby tb1dic.Value descending select tb1dic).ToDictionary(pair => pair.Key, pair => pair.Value);
            tb2 = (from tb2dic in tb2 orderby tb2dic.Value ascending select tb2dic).ToDictionary(pair => pair.Key, pair => pair.Value);
            JObject data = new();
            data.Add("tb1", JObject.FromObject(tb1));
            data.Add("tb2", JObject.FromObject(tb2));
            data.Add("tb1_sbmc", JArray.FromObject(tb1.Keys));
            data.Add("tb1_count", JArray.FromObject(tb1.Values));
            data.Add("tb2_sbmc", JArray.FromObject(tb2.Keys));
            data.Add("tb2_count", JArray.FromObject(tb2.Values));
            return RenderJson(data: data);
        }
    }
}
